<script>
	import {
		postAuthcodeLoginUUCS,
	} from "@/api/indexUUCS.js";
	import {
		getLoginByUsercode
	} from "@/api/indexApprove.js";
	import {
		postLoginOrderpByUsercode
	} from "@/api/indexOrderp.js";
	import {
		mapState,
	} from 'vuex';
	if (/Android|webOS|iPhone|iPod|BlackBerry/i.test(navigator.userAgent)) {
		var system = my.getSystemInfoSync();
		var ptf = system.platform.toUpperCase()
		var aplus = require('./utils/aplus_mini.js')({
			'metaInfo': {
				'appId': ptf == 'ANDROID' ? '28302650' : ptf == 'IOS' ? '28328447' : '47130293',
				'aplus-rhost-v': 'alog.zjzwfw.gov.cn',
				'aplus-rhost-g': 'alog.zjzwfw.gov.cn'
			}
		})
	}
	import dd from 'gdt-jsapi';
	var system = my.getSystemInfoSync();
	var ptf = system.platform.toUpperCase();
	var aplus = require('./utils/aplus_mini.js')({
		'metaInfo': {
			'appId': ptf == 'ANDROID' ? '28302650' : ptf == 'IOS' ? '28328447' : '47130293',
			'aplus-rhost-v': 'alog.zjzwfw.gov.cn',
			'aplus-rhost-g': 'alog.zjzwfw.gov.cn'
		}
	});
	// console.log(ptf)
	export default {
		data() {
			return {
				aplus: aplus,
				markerNum: [],
				userCode: '',
				// appName: 'Order-MApp',
				appName: 'UUCS',
				// corpId: '38685',  // 数空
				// corpId: '50127244', // 国遥
				// uucsHost: 'https://uucs.youlishu.com/backend/',
				// orderpHost: 'http://r740.youlishu.com:8886',
				// orderpWs: 'ws://r740.youlishu.com:8886',
				corpId: '196729',
				//真实环境
				uucsHost: 'https://uucs.dqbdsh.com/proxy/uucs2-backend',
				orderpHost: 'https://orderp.dqbdsh.com/proxy/orderp-backend',
				//测试环境
				// uucsHost: 'https://uucs.youlishu.com/backend/',
				// orderpHost: 'http://101.68.86.229:8880',
				orderpWs: 'wss://orderp.dqbdsh.com/proxy/orderp-backend',
			}
		},
		onLaunch: function() {
			console.log('App Launch')
			// 测试环境
			this.getAuthTokenDevelopment()
			// 生产环境
			// this.getAuthToken()
			// 生成authCode
			// dd.getAuthCode().then(res => { 
			// 	console.log('用户code: ', res)
			// }).catch(err => {
			// 	console.log('获取错误: ', err)
			// })
		},
		onShow: function() {
			// console.log('App Show')
		},
		onHide: function() {
			// console.log('App Hide')
		},
		computed: {
			...mapState(['userInfo']),
		},  
		methods: {
			// 线上环境登录
			getAuthToken() {
				return new Promise((resolve, reject) => {
					//线上调试
					my.getAuthCode({
						corpId: this.corpId
					}).then(res => {
            console.log('获取Token', res);
						// 异步埋点开启
						aplus.aplus_queue.push({
							action: 'aplus.setMetaInfo',
							arguments: ['_hold', 'BLOCK']
						});
						const authCode = res.result.code;
						console.log('获取到用户信息,开始用户信息埋点code', res.result.code)
						this.$store.commit('setAuthCode', authCode)
						console.log("auth_code: ", authCode);
						my.httpRequest({
							method: "POST",
							url: this.uucsHost + "/v2/dgapp/oauth/auth_code_login",
							data: {
								access_key: "jpSGMya3Jh",
								app_name: this.appName,
								auth_code: authCode,
								auth_for: "ding_gov_app"
							}
						}).then(res => {
							console.log('获取到用户信息,开始用户信息埋点uucsHost', res, JSON.stringify({
								access_key: "jpSGMya3Jh",
								app_name: this.appName,
								auth_code: authCode,
								auth_for: "ding_gov_app"
							}))
							if (res.data.success) {
								if (res.data.data.user_status === 'unactive') {
									my.hideLoading();
									// my.redirectTo({
									//   url: '/pages/active/active'
									// })
								} else {
									this.userCode = res.data.data.user_code;
									// 获取桃仁的token和用户信息
									getLoginByUsercode({
										userCode: this.userCode
									}).then(res => {
										console.log('桃仁登录:', res)
										this.$store.commit('mdApprove/setToken', res.token)
									})
									this.getlist(this.userCode)
									console.log('获取到用户信息,开始用户信息埋点0', this.userCode);
									this.getUserInfo(this.userCode).then(res => {
										my.hideLoading();
										console.log('获取到用户信息,开始用户信息埋点1', res);
										this.$store.commit('setUserInfo', res)
										console.log('获取到用户信息,开始用户信息埋点2', res);
										aplus.aplus_queue.push({
											action: 'aplus.setMetaInfo',
											arguments: ['_user_id', res
												.dingAccountId
											]
										});
										aplus.aplus_queue.push({
											action: 'aplus.setMetaInfo',
											arguments: ['_user_nick', res.realName]
										});
										aplus.aplus_queue.push({
											action: 'aplus.setMetaInfo',
											arguments: ['_hold', 'START']
										});
										resolve(res);
									});
								}
							}
						})
					}).catch(err => {
						console.log(4)
						console.log("免登接口出错", err);
					});
				})
			},
			// 测试环境用户信息
			async getAuthTokenDevelopment() {
				let userCode = ''
				await postAuthcodeLoginUUCS({
					access_key: "jpSGMya3Jh",
					app_name: this.appName,
					auth_code: 'w9mzrJMAiMKFnIVRpkdbdpqGnaxfefY2',
					auth_for: "ding_gov_app"
				}).then(codeRes => {
					console.log('authCode获取userCode:', codeRes)
					if (codeRes.user_status === 'unactive') {
						my.hideLoading();
					} else {
						userCode = codeRes.user_code;
						this.userCode = codeRes.user_code;
					}
				}).catch(err => {
					console.log(err)
					uni.showModal({
						title: '提示',
						content: err,
						success: function(res) {
							if (res.confirm) {
								console.log('用户点击确定');
							} else if (res.cancel) {
								console.log('用户点击取消');
							}
						}
					});
					return Promise.reject(err)
				})
				// 获取桃仁的token和用户信息
				getLoginByUsercode({
					userCode
				}).then(res => {
					console.log('桃仁登录:', res)
					this.$store.commit('mdApprove/setToken', res.token)
				})
				// 获取orderp用户信息
				this.getlist(userCode)
			},
			// 获取orderp用户信息
			async getlist(userCode) {
				postLoginOrderpByUsercode({
					userCode
				}).then(res => {
					console.log('orderp登录:', res)
					this.$store.commit('mdOrderp/setToken', res.token)
					uni.setStorageSync('userInfo', res)
					this.$store.commit('setUserInfo', res)
				}).catch(err => {
					console.log(err)
				})
			},
			getUserInfo(userCode) {
				// 获取用户信息
				return new Promise((resolve, reject) => {
					my.httpRequest({
						url: this.orderpHost + "/api/user/info",
						method: "GET",
						data: {
							userCode: userCode
						},
						complete: (res) => {
							this.connectWs(userCode);
							resolve(res.data.data);
						}
					})
				})
			},
			connectWs(token) {
				my.connectSocket({
					url: this.orderpWs + "/websocket/socketServer",
					data: {
						userCode: token
					},
					success: (res) => {
						// 返回 "{}",一个空的字典对象。
						console.log(JSON.stringify(res));
					},
					fail: () => {
						my.showToast({
							// 文字内容
							content: 'Websocket connect failed.',
						});
					}
				});
			},
			//高德地址信息
			getlocal() {
				var lnglat = [116.396574, 39.992706]
				amapPlugin.getRegeo({
					location: '' + lnglat[0] + ',' + lnglat[1] + '', //location的格式为'经度,纬度'
					//成功回调
					success: function(data) {
						console.log(data)
						// that.zuobiao.city = data[0].regeocodeData.addressComponent.city; //城市
						// that.zuobiao.district = data[0].regeocodeData.addressComponent.district;
						// that.zuobiao.province = data[0].regeocodeData.addressComponent.province;
						// uni.setStorageSync("zuobiao", that.zuobiao);
					},
					fail: function(info) {
						//失败回调
						console.log(info)
					}
				})
			}
		}
	}
</script>

<style lang="scss" scoped>
/*每个页面公共css */

@import "uview-ui/index.scss";
</style>
